package com.qzsoft.zhjd.server.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.qzsoft.zhjd.server.modules.glodon.gys.wl.mapper.CronTaskMapper;
import com.qzsoft.zhjd.server.modules.glodon.gys.wl.service.IGysQlWlPlatformService;
import com.qzsoft.zhjd.server.modules.glodon.gys.wl.service.IGysWlJdPlatformService;
import com.qzsoft.zhjd.server.modules.glodon.gys.wl.service.IGysWlWsPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 定时任务 配置
 */
@Slf4j
@Configuration
@EnableScheduling // 虽然多个不报错，但不推荐！
public class TimedTaskConfig implements SchedulingConfigurer {

    /**
     * 文双2
     */
    @Autowired
    private IGysWlWsPlatformService gysWlPlatformService;

    /**
     * 齐临
     */
    @Autowired
    private IGysQlWlPlatformService gysQlWlPlatformService;

    /**
     * 济德
     */
    @Autowired
    private IGysWlJdPlatformService gysWlJdPlatformService;

    @Lazy
    @Autowired
    private CronTaskMapper cronTaskMapper;

    @PostConstruct
    public void init() {
        log.info("[collect] >>> 加载启动定时任务！");
    }

    /**
     * 通常需要配置线程池
     * <p>
     * 支持多定时任务并行执行，防止相互干扰
     */
    @Override
    public void configureTasks(@NotNull ScheduledTaskRegistrar taskRegistrar) {
        // 创建一个线程池调度器
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 设置线程池大小
        taskScheduler.setPoolSize(10);
        // 设置线程名前缀
        taskScheduler.setThreadNamePrefix("scheduled-task-pool-");
        // 设置等待任务完成再关闭线程池
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间（单位：秒）
        taskScheduler.setAwaitTerminationSeconds(60);
        taskScheduler.initialize();

        taskRegistrar.setTaskScheduler(taskScheduler);

        // 最简单的 动态注册定时任务[未完工]！
        // List<CronTask> cronAll = cronTaskMapper.getCronAll();
        // cronAll.forEach(cronTask -> {
        //
        // });

        // taskRegistrar.addTriggerTask(
        //     //1.添加任务内容(Runnable)
        //     () -> System.out.println("执行动态定时任务1: " + LocalDateTime.now().toLocalTime() + ",此任务执行周期由数据库中的cron表达式决定"),
        //     //2.设置执行周期(Trigger)
        //     triggerContext -> {
        //         //2.1 从数据库获取执行周期
        //         String cron = cronMapper.getCron1();
        //         //2.2 合法性校验.
        //         if (cron!=null) {
        //             // Omitted Code ..
        //         }
        //         //2.3 返回执行周期(Date)
        //         return new CronTrigger(cron).nextExecutionTime(triggerContext);
        //     }
        // );

    }

    /**
     * 获取收料
     * <p>
     * 每5分钟执行一次！
     */
    @Async
    @Scheduled(cron = "0 30 * * * ?") // 每5分钟执行一次
    public void gysGetSLlist() {
        DateUtil now = new DateUtil();
        String formatted = DatePattern.PURE_DATETIME_MS_FORMAT.format(now);
        log.info("[TASK] - Time({}) >>> getSLlist执行！", now);
        try {
            gysWlPlatformService.getSLlist(null, formatted, false);

            gysQlWlPlatformService.getQLSLlist(null, formatted, false);

            gysWlJdPlatformService.getSLlist(null, formatted, false);
        } catch (Exception e) {
            log.error("[TASK] - Time({}) >>> getSLlist执行失败！", now, e);
        }
    }

    /**
     * 获取发料
     * <p>
     * 每5分钟执行一次！
     */
    @Async
    @Scheduled(cron = "0 30 * * * ?") // 每5分钟执行一次
    public void gysGetfLlist() {
        DateUtil now = new DateUtil();
        String formatted = DatePattern.PURE_DATETIME_MS_FORMAT.format(now);
        log.info("[TASK] - Time({}) >>> getFLlist执行！", now);
        try {
            gysWlPlatformService.getFLlist(null, formatted, false);

            gysQlWlPlatformService.getQLFLlist(null, formatted, false);

            gysWlJdPlatformService.getSLlist(null, formatted, false);
        } catch (Exception e) {
            log.error("[TASK] - Time({}) >>> getFLlist执行失败！", now, e);
        }
    }

    /**
     * 全天 补偿任务！
     * <p>
     * 每天 23:59:00 执行一次！
     */
    @Async
    @Scheduled(cron = "0 59 23 * * ?")
    public void allDayStandby() {
        Date now = new Date();
        DateTime beginOfDay = DateUtil.beginOfDay(now);
        String formatted = beginOfDay.toString(DatePattern.PURE_DATETIME_MS_FORMAT);
        log.info("[TASK] - Time({}) >>> allDayStandby执行！", beginOfDay);

        try {
            gysWlPlatformService.getSLlist(null, formatted, false);
            gysQlWlPlatformService.getQLSLlist(null, formatted, false);
        } catch (Exception e) {
            log.error("[TASK] - Time({}) >>> allDayStandby#getFLlist执行失败！", now, e);
        }

        try {
            gysWlPlatformService.getFLlist(null, formatted, false);
            gysQlWlPlatformService.getQLFLlist(null, formatted, false);
        } catch (Exception e) {
            log.error("[TASK] - Time({}) >>> allDayStandby#getFLlist执行失败！", now, e);
        }
    }

}
